package com.toutiao.cut.service;

import org.apache.thrift.TException;

import com.toutiao.cut.SemanticCutter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;


public class DocumentProcessImpl implements DocumentProcess.Iface {
	
	private static final Logger _log = Logger.getLogger(DocumentProcessImpl.class);

    private SemanticCutter cut;

    public DocumentProcessImpl(SemanticCutter cut){
        this.cut = cut;
    }

    private String process_cut(String line) {
        StringBuilder buffer = new StringBuilder();
        List<String> ns = cut.process(line);
        for (String n : ns){
            buffer.append(n).append(" ");
        }
        return buffer.toString().trim();
    }

    @Override
    public Map<String, String> process(Map<String, String> data) throws TException {
    	
    	long st = System.nanoTime();
    	
    	String i = "";
    	if (data.containsKey("id")){
    		i = data.get("id");
    	}
    	else if (data.containsKey("gid")) {
    		i = data.get("gid");
    	}    	
    	String r = "";
    	if (data.containsKey("req_name")){
    		r = data.get("req_name");
    	}

    	try {
            String title = "";
            if (data.containsKey("title")){
                title = data.get("title");
            }
            String content = "";
            if (data.containsKey("txt_content")){
                content = data.get("txt_content");
                int cc = 50000;
                if (content.length() > cc){
                	content = content.substring(0,cc);
                }
            }
            String source = "";
            if (data.containsKey("source")){
            	source = data.get("source");
            }

            String cut_title = process_cut(title);
            String[] split_content = content.split("\n");
            StringBuilder cut_content = new StringBuilder();
            for (String line: split_content){
                cut_content.append(process_cut(line)).append("\n");
            }

            Map<String,String> res_map = new HashMap<String,String>();
            res_map.put("cut_title",cut_title);
            res_map.put("cut_content",cut_content.toString().trim());
            
            String cut_source = process_cut(source);
            res_map.put("cut_source", cut_source);
            
            long et = System.nanoTime();
            _log.info(r+" "+i+" "+(et-st)/1e6+"ms");

            return res_map;    		
    	}
    	catch (Exception e) {
    		
    		_log.error(e.getMessage());
    		
    		Map<String,String> res_map = new HashMap<String,String>();
    		res_map.put("cut_title", "");
    		res_map.put("cut_content", "");
    		res_map.put("cut_source", "");

            long et = System.nanoTime();
            _log.info(r+" "+i+" "+(et-st)/1e6+"ms");    		
    		
    		return res_map;
    	}

    }
}
